#!/bin/bash
## 检查学生提交的作业
## 1. 读取学生列表
## 2. 为每个学生常见一个目录
## 3. 拉取对应的文件
## 4. 编译，运行对比结果

## 提示 下载wget 编译GCC 只要求字符比对
## 使用mktemp保证每个测试case下载不重复
## 延伸阅读: online judge

#BASEURL=https://github.com/guolb/junkcode/blob/master/linux/02_linux_command_intro/judge/fibonacci.c
# BASEURL_FORMAT=https://gitee.com/%s/linux_programing/raw/master/01_getting_started/%s
BASEURL_FORMAT=https://raw.githubusercontent.com/%s/junkcode/master/linux/02_linux_command_intro/judge/%s.c?token=AAXH2PK3NNE443LYWEV5FH27RMQYU
# USERNAME=guolb
USERNAME=${1-"guolb"}
SRC_FILE_NAME=fibonacci.c
SRC_URL=$(printf "$BASEURL_FORMAT" $USERNAME $SRC_FILE_NAME)

echo $SRC_URL
[ ! -d "$USERNAME" ] && mkdir "$USERNAME"
cd $USERNAME

##下载源代码
if [ -s "$SRC_FILE_NAME" ] || wget "$SRC_URL" -O $SRC_FILE_NAME; then
    echo "download source code success"
else
    echo "download source code fail"
    exit -1
fi

## 编译程序
APPNAME=app
if [ -f "$APPNAME" ] || gcc -o "$APPNAME" "$SRC_FILE_NAME"; then
    echo "compile success"
fi

## 生成测试用例输入文件
caseInFile=/tmp/in.txt
cat >$caseInFile <<EOF
1
3
7
9
EOF

## 生成正确答案文件
caseResultFile=/tmp/result.txt
cat >$caseResultFile <<EOF
1
2
13
34
EOF

## 将运行结果保存到文件
caseOutFile=/tmp/out.txt
rm -f $caseOutFile
for num in $(cat "$caseInFile"); do
    fib=$(echo "$num" | ./"$APPNAME")
    echo "$fib" >>$caseOutFile
done

### 比对运行结果和文件
if diff $caseOutFile $caseResultFile &>/dev/null; then
    echo "diff success, result correct"
else
    echo "diff fail, result not correct"
fi
